<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
define("LIMIT", empty(\think\Cache::get("config")['LIMIT']) ? "50" : \think\Cache::get("config")['LIMIT']);
define("APP_NAME", empty(\think\Cache::get("config")['APP_NAME']) ? "YoRHa" : \think\Cache::get("config")['APP_NAME']);
define("KEY", empty(\think\Cache::get("config")['KEY']) ? "zg0NjRlNzQwMDQyMWY4MjEzY2E4ZjYzZ" : \think\Cache::get("config")['KEY']);
define("UPLOAD", empty(\think\Cache::get("config")['UPLOAD']) ? "0" : \think\Cache::get("config")['UPLOAD']);
define("DOWNLOAD", empty(\think\Cache::get("config")['DOWNLOAD']) ? "0" : \think\Cache::get("config")['DOWNLOAD']);
define("PRICE", empty(\think\Cache::get("config")['PRICE']) ? "0" : \think\Cache::get("config")['PRICE']);
define("INV", empty(\think\Cache::get("config")['INV']) ? "0" : \think\Cache::get("config")['INV']);
define("INV_GROUP", empty(\think\Cache::get("config")['INV_GROUP']) ? "1" : \think\Cache::get("config")['INV_GROUP']);
define("VER", empty(\think\Cache::get("config")['VER']) ? time() : \think\Cache::get("config")['VER']);
define("TRACKER", empty(\think\Cache::get("config")['TRACKER']) ? "" : \think\Cache::get("config")['TRACKER']);
define("ENABLED_VERIFY", empty(\think\Cache::get("config")['ENABLED_VERIFY']) ? "on" : \think\Cache::get("config")['ENABLED_VERIFY']);
define("DISABLED_REG", empty(\think\Cache::get("config")['DISABLED_REG']) ? "off" : \think\Cache::get("config")['DISABLED_REG']);
define("DISABLED_INV", empty(\think\Cache::get("config")['DISABLED_INV']) ? "off" : \think\Cache::get("config")['DISABLED_INV']);
define("DISABLED_WEB", empty(\think\Cache::get("config")['DISABLED_WEB']) ? "off" : \think\Cache::get("config")['DISABLED_WEB']);
define("VERSION", "1.0.0");
define("COPYRIGHT", "YoRHa");

/**
 * $status 返回状态，0=失败（默认），1=成功，其它状态可自定义
 * $data 返回数据
 * $message 返回信息，字符串
 * $error_code 返回错误代号
 */
function jsonReturn($status = 0, $message = "", $data = "", $errorCode = 0, $arr = [])
{
	$result["status"] = $status;
	$result["message"] = $message;
	$result["data"] = $data;
	$result["error_code"] = $errorCode;
	if (!empty($arr)) {
		foreach ($arr as $k => $v) {
			$result[$k] = $v;
		}
	}
	echo json_encode($result);
	exit;
}

function nowtime()
{
	return date("Y-m-d H:i:s", time());
}

function ip()
{
	return \EasyWeChat\Payment\get_client_ip();
}

function getFullURL()
{
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$domainName = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

	return $protocol . $domainName;
}

function getWebURL()
{
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$domainName = $_SERVER['HTTP_HOST'];

	return $protocol . $domainName;
}

/**
 * @param string $url 请求网址
 * @param bool $params 请求参数，数组
 * @param int $ispost 请求方式
 * @param int $https https协议
 *
 * @return bool|mixed
 */
function mycurl($url, $params = FALSE, $ispost = 0, $https = 0)
{
	$httpInfo = array();
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	if ($https) {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
	}
	if ($ispost) {
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_setopt($ch, CURLOPT_URL, $url);
	} else {
		if ($params) {
			if (is_array($params)) {
				$params = http_build_query($params);
			}
			curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
		} else {
			curl_setopt($ch, CURLOPT_URL, $url);
		}
	}

	$response = curl_exec($ch);

	if ($response === FALSE) {
		//echo "cURL Error: " . curl_error($ch);
		return FALSE;
	}
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
	curl_close($ch);

	return $response;
}

/*
 * return $str
 */
function random($start = 7, $end = 32, $mixed = NULL, $case = 0, $min = 1, $max = 99999)
{
	if ($case == 1) {
		return substr(trim(base64_encode(sha1(mt_rand($min, $max) . uniqid(mt_rand(), TRUE) . $mixed))), $start, $end);
	} else {
		return strtolower(substr(trim(base64_encode(sha1(mt_rand($min, $max) . uniqid(mt_rand(), TRUE) . $mixed))), $start, $end));
	}
}

function getTorrentDB($type)
{
	if ($type == "m" || $type == "0") {
		return $dbname = "movie";
	} elseif ($type == "s" || $type == "1") {
		return $dbname = "series";
	}
}

function getSize($size)
{
	if ($size < 1024) {
		return $size . ' Byte';
	}
	if ($size < 1048576) {
		return round($size / 1024, 2) . ' KB';
	}
	if ($size < 1073741824) {
		return round($size / 1048576, 2) . ' MB';
	}
	if ($size < 1099511627776) {
		return round($size / 1073741824, 2) . ' GB';
	}
	if ($size < 1125899906842624) {
		return round($size / 1125899906842624, 2) . ' PB';
	}
	if ($size < 1152921504606846976) {
		return round($size / 1152921504606846976, 2) . ' EB';
	}
}

function discount($discount)
{
	switch ($discount) {
		case 1:
			return "Free";
			break;
		case 2:
			return "30%";
			break;
		case 3:
			return "50%";
			break;
		case 4:
			return "2x";
			break;
		case 5:
			return "2xFree";
			break;
		case 6:
			return "2x30%";
			break;
		case 7:
			return "2x50%";
			break;
		default:
			return NULL;
			break;
	}
}

function downloaded($num, $discount)
{
	switch ($discount) {
		case 1:
			return $num * 0;
			break;
		case 2:
			return round($num * 3 / 10);
			break;
		case 3:
			return round($num * 5 / 10);
			break;
		case 4:
			return $num * 1;
			break;
		case 5:
			return $num * 0;
			break;
		case 6:
			return round($num * 3 / 10);
			break;
		case 7:
			return round($num * 5 / 10);
			break;
		default:
			return $num * 1;
			break;
	}
}

function uploaded($num, $discount)
{
	switch ($discount) {
		case 1:
			return $num * 0;
			break;
		case 2:
			return $num * 0;
			break;
		case 3:
			return $num * 0;
			break;
		case 4:
			return $num * 2;
			break;
		case 5:
			return $num * 2;
			break;
		case 6:
			return $num * 2;
			break;
		case 7:
			return $num * 2;
			break;
		default:
			return $num * 1;
			break;
	}
}

function getContainer($id)
{
	\app\index\model\Container::getName($id);
}

function getResolution($id)
{
	\app\index\model\Resolution::getName($id);
}

function getSource($id)
{
	\app\index\model\Source::getName($id);
}

/**
 * @param $content
 * @param $controller
 * @param int $level，1 =日志，2=警告，其它自定义级别
 */
function logSave($content, $controller, $level = 1)
{
	$insert = [
		"level" => $level,
		"content" => $content,
		"controller" => $controller,
		"time" => nowtime()
	];
	db("log")->insert($insert);
}

function userLogSave($uid, $content, $level = 1)
{
	$insert = [
		"level" => $level,
		"content" => $content,
		"uid" => $uid,
		"time" => nowtime()
	];
	db("user_log")->insert($insert);
}

function mkPrettyTime($secs, $format = 0)
{
	$output = "";
	if ($format == 0) {
		$array = array(86400 => 'D ', 3600 => 'H ', 60 => 'M ', 1 => 's');
	} else {
		$array = array(86400 => '天', 3600 => '小时', 60 => '分钟', 1 => '秒');
	}
	foreach ($array as $key => $value) {
		if ($secs >= $key) {
			$output .= floor($secs / $key) . $value;
		}
		$secs %= $key;
	}

	if (!empty($output)) {
		return $output;
	} else {
		return "N/A";
	}
}

function getUserNameFromUID($uid)
{
	if ($uid != 0) {
		return db("users")->where("uid", $uid)->value("username");
	} else {
		return "无";
	}
}

function getIPAttr($ip)
{
	$res = json_decode(mycurl("http://ip.taobao.com/service/getIpInfo2.php", "ip=" . $ip, 1), TRUE);

	if ($res['code'] == 0 && $res['data']['area_id'] != "-1") {
		return $res['data']['country'] . $res['data']['isp'] . " " . $res['data']['region'] . $res['data']['city'];
	} else {
		return "";
	}
}

function getControllerAndAction()
{
	return request()->module() . "/" . request()->controller() . "/" . request()->action();
}

function getFieldName($field_name)
{
	switch ($field_name) {
		case "price":
			return "积分";
			break;
		case "email":
			return "邮箱";
			break;
		case "isadmin":
			return "用户组";
			break;
		case "ban":
			return "封禁状态";
			break;
		case "uuid":
			return "UUID";
			break;
		case "2fa":
			return "2FA";
			break;
		case "isnew":
			return "新人状态";
			break;
		case "hr":
			return "H&R";
			break;
		case "uploaded":
			return "上传量";
			break;
		case "downloaded":
			return "下载量";
			break;
		case "seedtime":
			return "总做种时间";
			break;
		case "leechtime":
			return "总下载时间";
			break;
		case "longinv":
			return "永久邀请数";
			break;
		case "shortinv":
			return "临时邀请数";
			break;
		case "softdel":
			return "软删除状态";
			break;
		case "extract":
			return "查看码";
			break;
		case "appid":
			return "APPID";
			break;
		case "appkey":
			return "APPKEY";
			break;
		default:
			break;
	}
}